

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言Django在处理接收到的 request 时, 会经过各种中间件的处理后, 才会轮到我们自定义的接口处理函数. 那么, 什么是中间件呢?  中间件顾名思义，是介于request与response处理之间的一道处理过程，相对比较轻量级，并且在全局上改变django的输入与输出。因为改变的是全局，所以需要谨慎使用. 目前我使用中间件时, 一般是用来定义项目规范&#x2F;统一化函数入参 如果你想修改请求，">
<meta property="og:type" content="article">
<meta property="og:title" content="Django中间件">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/12/14/notes/django/middleware/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言Django在处理接收到的 request 时, 会经过各种中间件的处理后, 才会轮到我们自定义的接口处理函数. 那么, 什么是中间件呢?  中间件顾名思义，是介于request与response处理之间的一道处理过程，相对比较轻量级，并且在全局上改变django的输入与输出。因为改变的是全局，所以需要谨慎使用. 目前我使用中间件时, 一般是用来定义项目规范&#x2F;统一化函数入参 如果你想修改请求，">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-12-14T05:57:40.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.250Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="测试平台">
<meta property="article:tag" content="后端框架">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Django中间件 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Django中间件"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-12-14 13:57" pubdate>
          2022年12月14日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          8.6k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Django中间件</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>Django在处理接收到的 request 时, 会经过各种<strong>中间件</strong>的处理后, 才会轮到我们自定义的接口处理函数.</p>
<p>那么, 什么是中间件呢? </p>
<p>中间件顾名思义，是介于request与response处理之间的一道处理过程，相对比较轻量级，并且在全局上改变django的输入与输出。因为改变的是全局，所以需要谨慎使用. 目前我使用中间件时, 一般是用来<strong>定义项目规范/统一化函数入参</strong></p>
<p>如果你想修改请求，例如被传送到view中的<strong>HttpRequest</strong>对象。 或者你想修改view返回的<strong>HttpResponse</strong>对象，这些都可以通过中间件来实现。</p>
<p>django框架内部声明了很多的中间件，这些中间件有着各种各种的用途，有些没有被使用，有些被默认开启使用了。而被开启使用的中间件，都是在settngs.py的MIDDLEWARE中注册使用的。</p>
<p>Django默认的<code>Middleware</code>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python">MIDDLEWARE = [<br>    <span class="hljs-string">&#x27;django.middleware.security.SecurityMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.contrib.sessions.middleware.SessionMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.middleware.common.CommonMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.middleware.csrf.CsrfViewMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.contrib.auth.middleware.AuthenticationMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.contrib.messages.middleware.MessageMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.middleware.clickjacking.XFrameOptionsMiddleware&#x27;</span>,<br>]<br></code></pre></td></tr></table></figure>

<h1 id="如何定义"><a href="#如何定义" class="headerlink" title="如何定义"></a>如何定义</h1><h2 id="定义一个中间件"><a href="#定义一个中间件" class="headerlink" title="定义一个中间件"></a>定义一个中间件</h2><p>比如说, 我们现在要创建一个全局的中间件.</p>
<p>可以在项目主目录中, 新建一个文件: <code>myMiddleware.py</code></p>
<p><strong>myProject/myMiddleware.py</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs Python"><span class="hljs-keyword">from</span> django.utils.deprecation <span class="hljs-keyword">import</span> MiddlewareMixin<br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Middleware</span>(<span class="hljs-title class_ inherited__">MiddlewareMixin</span>):<br>    ...<br></code></pre></td></tr></table></figure>

<p>中间件的声明, 是一个类, 这个类需要继承 Django 的 <strong>MiddlewareMixin</strong></p>
<h2 id="注册一个中间件"><a href="#注册一个中间件" class="headerlink" title="注册一个中间件"></a>注册一个中间件</h2><p>上面我们说到, Django有默认的中间件,注册在 settings 中.</p>
<p>所以我们自定义的中间件, 也需要去注册.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs Python">MIDDLEWARE = [<br>    <span class="hljs-string">&#x27;django.middleware.security.SecurityMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.contrib.sessions.middleware.SessionMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.middleware.common.CommonMiddleware&#x27;</span>,<br>    <span class="hljs-comment"># &#x27;django.middleware.csrf.CsrfViewMiddleware&#x27;,</span><br>    <span class="hljs-string">&#x27;django.contrib.auth.middleware.AuthenticationMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.contrib.messages.middleware.MessageMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;django.middleware.clickjacking.XFrameOptionsMiddleware&#x27;</span>,<br>    <span class="hljs-string">&#x27;myProject.myMiddleware.Middleware&#x27;</span>  <span class="hljs-comment"># 自定义的中间件</span><br>]<br></code></pre></td></tr></table></figure>

<p>中间件的处理顺序, 是根据 <strong>MIDDLEWARE</strong> 的注册顺序来的.</p>
<p>也就是说, 我们自定义的中间件, 在拿到请求进行处理时, 实际上已经是被Django默认的中间件处理过一轮了.</p>
<h1 id="中间件处理函数"><a href="#中间件处理函数" class="headerlink" title="中间件处理函数"></a>中间件处理函数</h1><p>只针对http请求处理, 一共有四种函数可以进行定义:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs Python">process_request(self,request)<br>process_view(self, request, view_func, view_args, view_kwargs)<br>process_exception(self, request, exception)<br>process_response(self, request, response)<br></code></pre></td></tr></table></figure>

<p>执行时机:</p>
<ul>
<li>process_request, 在匹配路由前调用</li>
<li>process_view, 在执行视图函数前调用</li>
<li>process_response, 在返回响应时调用</li>
<li>process_exception, 函数处理发生异常时调用.</li>
</ul>
<h2 id="process-request"><a href="#process-request" class="headerlink" title="process_request"></a>process_request</h2><p>在匹配路由前调用, 主要的用途就是过滤请求.</p>
<p>所以我们可以通过该函数进行token等身份校验.</p>
<p>或者可以过滤黑名单ip.</p>
<ul>
<li>返回值是 None 的话，按正常流程继续走.</li>
<li>返回值是 response 对象，Django 将中断请求处理,直接进行响应返回.</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs Python"><span class="hljs-keyword">from</span> django.utils.deprecation <span class="hljs-keyword">import</span> MiddlewareMixin<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Middleware</span>(<span class="hljs-title class_ inherited__">MiddlewareMixin</span>):<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_request</span>(<span class="hljs-params">self, request</span>): <span class="hljs-comment"># 在视图之前执行</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;md1  process_request 方法。&quot;</span>, <span class="hljs-built_in">id</span>(request))<br>        token = request.META.get(<span class="hljs-string">&#x27;HTTP_ACESS_TOKEN&#x27;</span>)<br>        <span class="hljs-keyword">if</span> token:<br>            <span class="hljs-comment"># ... 可以在这进行token校验</span><br>            <br>            <span class="hljs-built_in">print</span>(token)<br>        <span class="hljs-keyword">else</span>:<br>            <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 该请求未携带token, 不予处理!&#x27;</span><br>            &#125;)<br></code></pre></td></tr></table></figure>

<p>这个时候, 如果请求的header中未声明请求头 <code>acess-token</code>, 接口将会响应</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;msg&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;警告! 该请求未携带token, 不予处理!&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;code&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">403</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h2 id="process-view"><a href="#process-view" class="headerlink" title="process_view"></a>process_view</h2><p>在执行视图函数前调用</p>
<p>所以我们可以用来解析请求参数, 或者限定请求方式.</p>
<p>process_view 方法有四个参数：</p>
<ul>
<li>request 是 HttpRequest 对象。</li>
<li>view_func 是 Django 即将使用的视图函数。</li>
<li>view_args 是将传递给视图的位置参数的列表。</li>
<li>view_kwargs 是将传递给视图的关键字参数的字典。</li>
</ul>
<p>处理逻辑:</p>
<ul>
<li>返回值是 None 的话，按正常流程继续走，交给下一个中间件处理。</li>
<li>返回值是 response 对象，Django 将中断请求处理,直接进行响应返回。</li>
<li>返回值是 view_func，Django 将直接执行接口处理函数。</li>
</ul>
<p><strong>view_args/view_kwargs</strong> 目前对我们的学习方式来说, 暂时用不到.</p>
<p>因为这个涉及路由匹配的写法以及Django模板, 并不打算像大家介绍这一方面的知识,有兴趣的可以下去了解.原因就是我们后续的开发模式是 <strong>前后端分离</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><code class="hljs Python"><span class="hljs-keyword">import</span> json<br><br><span class="hljs-keyword">from</span> django.utils.deprecation <span class="hljs-keyword">import</span> MiddlewareMixin<br><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> JsonResponse<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Middleware</span>(<span class="hljs-title class_ inherited__">MiddlewareMixin</span>):<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_request</span>(<span class="hljs-params">self, request</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;md1  process_request 方法。&quot;</span>, <span class="hljs-built_in">id</span>(request))  <span class="hljs-comment"># 在视图之前执行</span><br><br>        token = request.META.get(<span class="hljs-string">&#x27;HTTP_ACESS_TOKEN&#x27;</span>)<br>        <span class="hljs-keyword">if</span> token:<br>            <span class="hljs-comment"># ... 可以在这进行token校验</span><br>            <br>            <span class="hljs-built_in">print</span>(token)<br>        <span class="hljs-keyword">else</span>:<br>            <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 该请求未携带token, 不予处理!&#x27;</span>,<br>                <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">403</span><br>            &#125;)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_view</span>(<span class="hljs-params">self, request, view_func, view_args, view_kwargs</span>):<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> request.method <span class="hljs-keyword">in</span> [<span class="hljs-string">&#x27;POST&#x27;</span>, <span class="hljs-string">&#x27;GET&#x27;</span>]:<br>            <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 不允许该请求方式, 允许的请求方式: POST|GET&#x27;</span>,<br>                <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>            &#125;)<br>        <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">&#x27;GET&#x27;</span>:<br>            request.requestData = request.GET<br>        <span class="hljs-keyword">else</span>:<br>            contentType = request.META.get(<span class="hljs-string">&#x27;CONTENT_TYPE&#x27;</span>)<br>            <span class="hljs-keyword">if</span> contentType:<br>                <span class="hljs-keyword">if</span> <span class="hljs-string">&#x27;multipart/form-data&#x27;</span> <span class="hljs-keyword">in</span> contentType:<br>                    request.requestData = request.POST<br>                <span class="hljs-keyword">elif</span> <span class="hljs-string">&#x27;application/json&#x27;</span> <span class="hljs-keyword">in</span> contentType:<br>                    request.requestData = json.loads(request.body)<br>                <span class="hljs-keyword">else</span>:<br>                    <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                        <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 请求头[content-type]需要指定 [multipart/form-data] 或 [application/json]&#x27;</span>,<br>                        <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>                    &#125;)<br>            <span class="hljs-keyword">else</span>:<br>                <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                    <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 请求头中需要包含[content-type]&#x27;</span>,<br>                    <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>                &#125;)<br></code></pre></td></tr></table></figure>

<p>通过 <code>process_view</code> 解析接口参数后, 我们的接口函数可以直接以字典取值的方式直接使用参数.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>(<span class="hljs-params">request</span>):<br>    <span class="hljs-built_in">print</span>(request.requestData)<br>    <span class="hljs-keyword">return</span> JsonResponse(request.requestData)<br></code></pre></td></tr></table></figure>

<h2 id="process-response"><a href="#process-response" class="headerlink" title="process_response"></a>process_response</h2><p>process_response 方法有两个参数，一个是 request，一个是 response.</p>
<p>该方法必须要有返回值，且必须是response。</p>
<p>我们可以用来判断针对某些接口来返回某些特定的信息.</p>
<p>比如:</p>
<ul>
<li>针对登录接口,返回token.</li>
<li>针对下载文件类型, 添加请求头.</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> json<br><br><span class="hljs-keyword">from</span> django.utils.deprecation <span class="hljs-keyword">import</span> MiddlewareMixin<br><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> JsonResponse, FileResponse<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Middleware</span>(<span class="hljs-title class_ inherited__">MiddlewareMixin</span>):<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_request</span>(<span class="hljs-params">self, request</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;md1  process_request 方法。&quot;</span>, <span class="hljs-built_in">id</span>(request))  <span class="hljs-comment"># 在视图之前执行</span><br><br>        token = request.META.get(<span class="hljs-string">&#x27;HTTP_ACESS_TOKEN&#x27;</span>)<br>        <span class="hljs-keyword">if</span> token:<br>            <span class="hljs-comment"># ... 可以在这进行token校验</span><br>            <br>            <span class="hljs-built_in">print</span>(token)<br>        <span class="hljs-keyword">else</span>:<br>            <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 该请求未携带token, 不予处理!&#x27;</span>,<br>                <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">403</span><br>            &#125;)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_view</span>(<span class="hljs-params">self, request, view_func, view_args, view_kwargs</span>):<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> request.method <span class="hljs-keyword">in</span> [<span class="hljs-string">&#x27;POST&#x27;</span>, <span class="hljs-string">&#x27;GET&#x27;</span>]:<br>            <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 不允许该请求方式, 允许的请求方式: POST|GET&#x27;</span>,<br>                <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>            &#125;)<br>        <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">&#x27;GET&#x27;</span>:<br>            request.requestData = request.GET<br>        <span class="hljs-keyword">else</span>:<br>            contentType = request.META.get(<span class="hljs-string">&#x27;CONTENT_TYPE&#x27;</span>)<br>            <span class="hljs-keyword">if</span> contentType:<br>                <span class="hljs-keyword">if</span> <span class="hljs-string">&#x27;multipart/form-data&#x27;</span> <span class="hljs-keyword">in</span> contentType:<br>                    request.requestData = request.POST<br>                <span class="hljs-keyword">elif</span> <span class="hljs-string">&#x27;application/json&#x27;</span> <span class="hljs-keyword">in</span> contentType:<br>                    request.requestData = json.loads(request.body)<br>                <span class="hljs-keyword">else</span>:<br>                    <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                        <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 请求头[content-type]需要指定 [multipart/form-data] 或 [application/json]&#x27;</span>,<br>                        <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>                    &#125;)<br>            <span class="hljs-keyword">else</span>:<br>                <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                    <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 请求头中需要包含[content-type]&#x27;</span>,<br>                    <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>                &#125;)<br>        <br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_response</span>(<span class="hljs-params">self, request, response</span>):<br>        <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(response, FileResponse):<br>            response[<span class="hljs-string">&#x27;Content-Type&#x27;</span>] = <span class="hljs-string">&#x27;application/octet-stream&#x27;</span><br>            response[<span class="hljs-string">&#x27;Content-Disposition&#x27;</span>] = <span class="hljs-string">f&#x27;attachment;filename=&quot;<span class="hljs-subst">&#123;response.fileName&#125;</span>&quot;&#x27;</span><br>        <span class="hljs-keyword">return</span> response<br></code></pre></td></tr></table></figure>

<h2 id="process-exception"><a href="#process-exception" class="headerlink" title="process_exception"></a>process_exception</h2><p>process_exception 方法只有在视图函数中出现异常了才执行</p>
<p>process_exception 方法的返回值可以是一个 None 也可以是一个 HttpResponse 对象。</p>
<p><strong>返回值是 None，页面会报 500 状态码错误，视图函数不会执行。</strong></p>
<p><strong>返回值是 HttpResponse 对象，页面不会报错，返回状态码为 200。</strong></p>
<p><em><strong>注意!</strong></em></p>
<blockquote>
<p>若是 process_view 方法返回视图函数，提前执行了视图函数，且视图函数报错，则无论 process_exception 方法的返回值是什么，页面都会报错， 且视图函数和 process_exception 方法都不执行。<br>所以我们在process_view中, 是在 <strong>request</strong> 的身上增加 <strong>reqeustData</strong> 属性</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> json<br><br><span class="hljs-keyword">from</span> django.utils.deprecation <span class="hljs-keyword">import</span> MiddlewareMixin<br><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> JsonResponse, FileResponse<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Middleware</span>(<span class="hljs-title class_ inherited__">MiddlewareMixin</span>):<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_request</span>(<span class="hljs-params">self, request</span>):<br>        <span class="hljs-comment"># print(&quot;md1  process_request 方法。&quot;, id(request))  # 在视图之前执行</span><br><br>        token = request.META.get(<span class="hljs-string">&#x27;HTTP_ACESS_TOKEN&#x27;</span>)<br>        <span class="hljs-keyword">if</span> token:<br>            <span class="hljs-comment"># ... 可以在这进行token校验</span><br>            ...<br>            <span class="hljs-comment"># print(token)</span><br>        <span class="hljs-keyword">else</span>:<br>            <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 该请求未携带token, 不予处理!&#x27;</span>,<br>                <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">403</span><br>            &#125;)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_view</span>(<span class="hljs-params">self, request, view_func, view_args, view_kwargs</span>):<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> request.method <span class="hljs-keyword">in</span> [<span class="hljs-string">&#x27;POST&#x27;</span>, <span class="hljs-string">&#x27;GET&#x27;</span>]:<br>            <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 不允许该请求方式, 允许的请求方式: POST|GET&#x27;</span>,<br>                <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>            &#125;)<br>        <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">&#x27;GET&#x27;</span>:<br>            request.requestData = request.GET<br>        <span class="hljs-keyword">else</span>:<br>            contentType = request.META.get(<span class="hljs-string">&#x27;CONTENT_TYPE&#x27;</span>)<br>            <span class="hljs-keyword">if</span> contentType:<br>                <span class="hljs-keyword">if</span> <span class="hljs-string">&#x27;multipart/form-data&#x27;</span> <span class="hljs-keyword">in</span> contentType:<br>                    request.requestData = request.POST<br>                <span class="hljs-keyword">elif</span> <span class="hljs-string">&#x27;application/json&#x27;</span> <span class="hljs-keyword">in</span> contentType:<br>                    request.requestData = json.loads(request.body)<br>                <span class="hljs-keyword">else</span>:<br>                    <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                        <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 请求头[content-type]需要指定 [multipart/form-data] 或 [application/json]&#x27;</span>,<br>                        <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>                    &#125;)<br>            <span class="hljs-keyword">else</span>:<br>                <span class="hljs-keyword">return</span> JsonResponse(&#123;<br>                    <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-string">&#x27;警告! 请求头中需要包含[content-type]&#x27;</span>,<br>                    <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">500</span><br>                &#125;)<br>        <br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_response</span>(<span class="hljs-params">self, request, response</span>):<br>        <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(response, FileResponse):<br>            response[<span class="hljs-string">&#x27;Content-Type&#x27;</span>] = <span class="hljs-string">&#x27;application/octet-stream&#x27;</span><br>            response[<span class="hljs-string">&#x27;Content-Disposition&#x27;</span>] = <span class="hljs-string">f&#x27;attachment;filename=&quot;<span class="hljs-subst">&#123;response.fileName&#125;</span>&quot;&#x27;</span><br>        <span class="hljs-keyword">return</span> response<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">process_exception</span>(<span class="hljs-params">self, request, exception</span>):<br>        responseDict = &#123;<br>            <span class="hljs-string">&#x27;msg&#x27;</span>: <span class="hljs-built_in">str</span>(exception),<br>            <span class="hljs-string">&#x27;code&#x27;</span>: <span class="hljs-number">0</span><br>        &#125;<br>        <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(exception, ValueError):  <span class="hljs-comment"># 自定义状态码返回, 这可以当作项目规范</span><br>            responseDict[<span class="hljs-string">&#x27;code&#x27;</span>] = <span class="hljs-number">5001</span><br>        <br>        <span class="hljs-keyword">return</span> JsonResponse(responseDict)<br></code></pre></td></tr></table></figure>

<p>这个时候, 如果你在接口逻辑处理函数中手动抛出 <code>raise ValueError</code></p>
<p>你将会收到响应 </p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;msg&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;$error msg&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;code&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5001</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<p>你也可以 <strong>自定义异常</strong>, 来面对更多异常情况</p>
<p>比如:</p>
<ul>
<li>token异常</li>
<li>业务异常</li>
<li>参数异常</li>
</ul>
<p><strong>如何自定义异常? 可以参考博客文章: <a href="https://walker_kwu.gitee.io/my-blog/2022/07/11/python/basic/try-except/">https://walker_kwu.gitee.io/my-blog/2022/07/11/python/basic/try-except/</a></strong></p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/" class="category-chain-item">测试开发</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/Django/" class="category-chain-item">Django</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%B9%B3%E5%8F%B0/">#测试平台</a>
      
        <a href="/my-blog/tags/%E5%90%8E%E7%AB%AF%E6%A1%86%E6%9E%B6/">#后端框架</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Django中间件</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/12/14/notes/django/middleware/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年12月14日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2023/02/18/env/java/" title="java环境配置（windows）">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">java环境配置（windows）</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2022/12/12/notes/django/ormAction/" title="Django-ORM操作进阶">
                        <span class="hidden-mobile">Django-ORM操作进阶</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
